<template>
  <div class="app-container">
    <div v-if="device !== 'mobile'">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="发版名称" prop="fbName">
          <el-input
            v-model="queryParams.fbName"
            placeholder="请输入发版名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="发版日期" prop="fbDate">
          <el-date-picker clearable
                          v-model="queryParams.fbDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择发版日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发版类型" prop="fbType">
          <el-select v-model="queryParams.fbType" placeholder="请选择发版类型" clearable>
            <el-option
              v-for="dict in dict.type.yjcz_fb_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['yjcz:fbInfo:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['yjcz:fbInfo:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['yjcz:fbInfo:remove']"
          >删除</el-button>
        </el-col>
<!--        <el-col :span="1.5">-->
<!--          <el-button-->
<!--            type="warning"-->
<!--            plain-->
<!--            icon="el-icon-download"-->
<!--            size="mini"-->
<!--            @click="handleExport"-->
<!--            v-hasPermi="['yjcz:fbInfo:export']"-->
<!--          >导出</el-button>-->
<!--        </el-col>-->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="fbInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="发版名称" align="center" prop="fbName" />
        <el-table-column label="发版日期" align="center" prop="fbDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.fbDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发版类型" align="center" prop="fbType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.yjcz_fb_type" :value="scope.row.fbType"/>
          </template>
        </el-table-column>
        <el-table-column label="发版系统" align="center" prop="channelListNames" />
        <el-table-column label="带班领导" align="center" prop="fbTeamLeaderName" />
        <el-table-column label="总控" align="center" prop="fbGeneralControlName" />
        <el-table-column label="备注" align="center" prop="fbRemark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['yjcz:fbInfo:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['yjcz:fbInfo:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改发版版本信息对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="发版名称" prop="fbName">
            <el-input v-model="form.fbName" placeholder="请输入发版名称" />
          </el-form-item>
          <el-form-item label="发版日期" prop="fbDate">
            <el-date-picker clearable
                            v-model="form.fbDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择发版日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="发版类型" prop="fbType">
            <el-select v-model="form.fbType" placeholder="请选择发版类型">
              <el-option
                v-for="dict in dict.type.yjcz_fb_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发版应用系统" prop="channelListIds">
            <el-select v-model="form.channelListIds" filterable multiple placeholder="请选择应用系统">
              <el-option
                v-for="item in channelList"
                :key="item.pkId"
                :label="item.channelName"
                :value="parseInt(item.pkId)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="带班领导" prop="fbTeamLeader">
            <el-select v-model="form.fbTeamLeader" filterable placeholder="请选择带班领导">
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="总控" prop="fbGeneralControl">
            <el-select v-model="form.fbGeneralControl" filterable placeholder="请选择总控">
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="fbRemark">
            <el-input v-model="form.fbRemark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
    <div v-if="device === 'mobile'">
      <van-form>
        <van-field
          v-model="queryParams.fbName"
          name="发版名称"
          label="发版名称"
          placeholder="发版名称"
        />
        <van-field
          readonly
          clickable
          name="calendar"
          :value="queryParams.fbDate"
          label="发版日期"
          placeholder="点击选择日期"
          @click="mobilePluginsProp.showCal = true"
        />
        <van-calendar v-model="mobilePluginsProp.showCal" :show-confirm="false" @confirm="onConfirm">
          <template slot="footer">
            <div class="btns">
              <van-button class="filter-time_btn" type="info" @click="onCancelCalendar">清空</van-button>
            </div>
          </template>
        </van-calendar>
        <van-field
          readonly
          clickable
          name="picker"
          :value="mobilePluginsProp.fbTypeName"
          label="发版类型"
          placeholder="点击选择发版类型"
          @click="mobilePluginsProp.showPicker = true"
        />
        <van-popup v-model="mobilePluginsProp.showPicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="dict.type.yjcz_fb_type"
            value-key="label"
            @confirm="onConfirmFbType"
            @cancel="onCancelFbType"
          />
        </van-popup>
        <div style="margin: 16px;">
          <!-- 居中 -->
          <van-row type="flex" justify="center">
            <van-col span="8">
              <van-button style="width: 100%" round type="info" native-type="submit" @click="mobileGetList(true)" icon="search">
                搜索
              </van-button>
            </van-col>
            <van-col span="2">
            </van-col>
            <van-col span="8">
              <van-button style="width: 100%" round type="default" @click="resetAndGetList" icon="replay">
                重置
              </van-button>
            </van-col>
          </van-row>
        </div>
      </van-form>
      <van-list
        v-model="mobilePluginsProp.loading"
        :finished="mobilePluginsProp.finished"
        finished-text="没有更多了"
        @load="mobileGetList"
      >
        <van-collapse v-model="mobilePluginsProp.activeNames">
          <van-swipe-cell v-for="item in fbInfoList">
            <van-collapse-item :title="item.fbName + '（' + item.fbDate + '）'" :key="item.pkId">
              <van-cell-group>
                <van-cell :title="'发版名称：' + item.fbName" />
                <van-cell :title="'发版时间：' + item.fbDate" />
                <van-cell :title="'发版类型：' + item.fbTypeName" />
                <van-cell :title="'发版应用系统：' + (null == item.channelListNames ? '无' : item.channelListNames)" />
                <van-cell :title="'带班领导：' + (null == item.fbTeamLeaderName ? '无' : item.fbTeamLeaderName)" />
                <van-cell :title="'总控：' + (null == item.fbGeneralControlName ? '无' : item.fbGeneralControlName)" />
                <van-cell :title="'备注：' + (null == item.fbRemark ? '无' : item.fbRemark)" />
              </van-cell-group>
            </van-collapse-item>
            <template #right>
              <van-button square type="primary" text="修改" @click="mobileModify(item)" icon="edit" />
              <van-button square type="danger" text="删除" @click="handleDelete(item)" icon="close" />
            </template>
          </van-swipe-cell>
        </van-collapse>
      </van-list>

      <van-dialog v-model="mobilePluginsProp.showAddOrModDialog" :title="mobilePluginsProp.dialogTitle" :showCancelButton="true" :showConfirmButton="false" style="height: 90%; overflow-y: auto">
          <van-form validate-first @failed="onFailed" @submit="onSubmitMobileForm">
            <!-- 通过 pattern 进行正则校验 -->
            <van-field
              name="发版名称"
              label="发版名称"
              placeholder="发版名称"
              v-model="form.fbName"
              :rules="[{ required: true, message: '请填写发版名称' }, { min: 3, max: 50, message: '长度在 3 到 50 个字符'}]"
            />

            <van-calendar-input
              label="发版日期"
              placeholder="点击选择日期"
              :value="form.fbDate"
              :rules="[{ required: true, message: '发版日期不能为空'}]"
              @confirm="onAddCalConfirm"
              @cancel="onCancelAddCalendar"
            />

            <van-field-select-picker
              v-model="form.fbType"
              label="发版类型"
              placeholder="点击选择发版类型"
              :columns="dict.type.yjcz_fb_type"
              :option="{label:'label',value:'value'}"
              :isSearch="true"
              @confirm="onConfirmAddFbType"
              :rules="[{ required: true, message: '发版类型不能为空'}]"
            />


            <van-field-checkbox
              label="发版应用系统"
              placeholder="请选择发版应用系统"
              v-model="form.channelListIds"
              :columns="channelList"
              :option="{label:'channelName',value:'pkId'}"
              @confirm="onChannelSelectConfirm"
              :rules="[{ required: true, message: '发版应用系统不能为空'}]"
            />

            <van-field-select-picker
              v-model="form.fbTeamLeader"
              label="带班领导"
              placeholder="点击选择带班领导"
              :columns="userList"
              :option="{label:'nickName',value:'userId'}"
              :isSearch="true"
              @confirm="onConfirmAddTeamLeader"
            />

            <van-field-select-picker
              v-model="form.fbGeneralControl"
              label="总控"
              placeholder="点击选择总控"
              :columns="userList"
              :option="{label:'nickName',value:'userId'}"
              :isSearch="true"
              @confirm="onConfirmAddControlLeader"
            />


            <van-field
              name="备注"
              label="备注"
              placeholder="备注"
              v-model="form.fbRemark"
            />
            <div style="margin: 16px;">
              <van-button round block type="info" native-type="submit">
                提交
              </van-button>
            </div>
          </van-form>
      </van-dialog>

      <van-button block type="info" @click="mobileAdd" style="position: fixed; bottom: 0px; z-index: 2; left: 0px" icon="plus">
        新增
      </van-button>
    </div>
  </div>
</template>

<script>
import { listFbInfo, getFbInfo, delFbInfo, addFbInfo, updateFbInfo, listUser, listChannel } from "@/api/yjcz/fbInfo";
import {mapState} from "vuex";
import {Dialog, Notify} from "vant";
import VanFieldSelectPicker from "@/components/VantTools/VanFieldSelectPicker";
import VanFieldCheckbox from "@/components/VantTools/VanFieldCheckbox";
import VanCalendarInput from "@/components/VantTools/VanCalendarInput";


export default {
  name: "FbInfo",
  dicts: ['yjcz_fb_type'],
  components: { VanFieldSelectPicker, VanFieldCheckbox, VanCalendarInput },
  computed: {
    ...mapState({
      device: state => state.app.device,
    })
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发版版本信息表格数据
      fbInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fbName: null,
        fbDate: null,
        fbType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        fbName: [
          { required: true, message: "发版名称不能为空", trigger: "blur" },
          { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        fbDate: [
          { required: true, message: "发版日期不能为空", trigger: "blur" }
        ],
        fbType: [
          { required: true, message: "发版类型不能为空", trigger: "change" }
        ],
        channelListIds: [
          { required: true, message: "发版应用系统不能为空", trigger: "change" }
        ],
      },
      userList: [],
      channelList: [],
      mobilePluginsProp: {
        showCal: false,
        showPicker: false,
        fbTypeName: '',
        loading: false,
        finished: false,
        activeNames: [],
        showAddOrModDialog: false,
        dialogTitle: '新增版本信息',
        showAddCal: false,
        showAddFbTypePicker: false,
        showAddTeamLeaderPicker: false,
        showAddControlPicker: false
      }
    };
  },
  created() {
    this.$nextTick(() => {
      if (this.device !== 'mobile') {
        this.getList();
      }
    })
  },
  methods: {
    /** 查询发版版本信息列表 */
    getList() {
      this.loading = true;
      listFbInfo(this.queryParams).then(response => {
        this.fbInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        pkId: null,
        fbName: null,
        fbDate: null,
        fbType: null,
        fbTeamLeader: null,
        fbTeamLeaderName: null,
        fbGeneralControl: null,
        fbGeneralControlName: null,
        fbRemark: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.pkId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getUserList()
      this.getChannelList()
      this.open = true;
      this.title = "添加发版版本信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getUserList()
      this.getChannelList()
      const pkId = row.pkId || this.ids
      getFbInfo(pkId).then(response => {
        this.form = response.data;
        this.form.channelListIds = this.handleSelectIds(this.form.channelListIds)
        this.open = true;
        this.title = "修改发版版本信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (typeof this.form.channelListIds === 'object') {
        this.form.channelListIds = this.form.channelListIds.join(',')
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.pkId != null) {
            updateFbInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFbInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const pkIds = row.pkId || this.ids;
      if (this.device === 'mobile') {
        Dialog.confirm({
          title: '确认删除发版信息',
          message: '是否确认删除发版版本信息？',
        }).then(() => {
          // on confirm
          return delFbInfo(pkIds);
        }).then(() => {
          var index = 0
          for (var i = 0; i < this.fbInfoList.length; i ++) {
            if (this.fbInfoList[i].pkId === pkIds) {
              index = i + 1
              break
            }
          }
          var pageSize = this.queryParams.pageSize
          var delPageIndex = parseInt(index / pageSize)
          delPageIndex = (index % pageSize == 0) ? delPageIndex : (delPageIndex + 1)
          var newFbInfoList = []
          if (delPageIndex > 1) {
            newFbInfoList = this.fbInfoList.slice(0, pageSize * (delPageIndex - 1))
          }
          this.queryParams.pageNum = delPageIndex
          this.getFbListCommon(newFbInfoList)
          if (!this.mobilePluginsProp.finished) {
            this.queryParams.pageNum ++
            this.getFbListCommon(newFbInfoList)
          }
          this.fbInfoList = newFbInfoList
          Notify({ type: 'success', message: '删除成功' });
        })
        return
      }
      this.$modal.confirm('是否确认删除发版版本信息？').then(function() {
        return delFbInfo(pkIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('yjcz/fbInfo/export', {
        ...this.queryParams
      }, `fbInfo_${new Date().getTime()}.xlsx`)
    },
    /** 查询用户列表 */
    getUserList () {
      listUser().then(response => {
        if (response.code === 200) {
          this.userList = response.data
        }
      })
    },
    getChannelList () {
      listChannel().then(response => {
        if (response.code === 200) {
          this.channelList = response.data
        }
      })
    },
    onConfirm(date) {
      this.mobilePluginsProp.showCal = false;
      this.queryParams.fbDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    },
    onAddCalConfirm (date) {
      this.form.fbDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    },
    onCancelCalendar () {
      this.mobilePluginsProp.showCal = false;
      this.queryParams.fbDate = ''
    },
    onCancelAddCalendar () {
      this.form.fbDate = ''
    },
    onConfirmFbType (value) {
      this.queryParams.fbType = value.value
      this.mobilePluginsProp.fbTypeName = value.label
      this.mobilePluginsProp.showPicker = false
    },
    onCancelFbType () {
      this.queryParams.fbType = ''
      this.mobilePluginsProp.fbTypeName = ''
      this.mobilePluginsProp.showPicker = false
    },
    onConfirmAddFbType (value) {
      this.form.fbType = value.value
    },
    onChannelSelectConfirm (value) {
      this.form.channelListIds = value
    },
    onConfirmAddTeamLeader (value) {
      this.form.fbTeamLeader = value.userId
    },
    onConfirmAddControlLeader (value) {
      this.form.fbGeneralControl = value.userId
    },
    mobileGetList (isResetPage) {
      if (isResetPage) {
        this.queryParams.pageNum = 1;
        this.fbInfoList = []
      }
      this.getFbListCommon(this.fbInfoList)
    },
    getFbListCommon (fbInfoList) {
      this.mobilePluginsProp.loading = true
      listFbInfo(this.queryParams).then(response => {
        const rows = response.rows
        this.formatFbType(rows, fbInfoList)
        this.total = response.total;
        this.mobilePluginsProp.loading = false;
        if (fbInfoList.length === this.total) {
          this.mobilePluginsProp.finished = true
        } else {
          this.queryParams.pageNum ++
        }
      });
    },
    resetAndGetList () {
      Object.assign(this.queryParams, {
        fbName: null,
        fbType: null,
        fbDate: null
      })
      this.mobilePluginsProp.fbTypeName = ''
      this.mobileGetList(true)
    },
    formatFbType (rows, fbInfoList) {
      if (rows && rows.length > 0) {
        rows.forEach(r => {
          this.formatFbTypeCommon(r)
          fbInfoList.push(r)
        })
      }
    },
    formatFbTypeCommon (r) {
      const fbTypeDicts = this.dict.type.yjcz_fb_type
      const fbTypeArr = fbTypeDicts.filter(d => d.value == r.fbType)
      if (fbTypeArr && fbTypeArr.length > 0) {
        r.fbTypeName = fbTypeArr[0].label
      }
    },
    mobileAdd () {
      this.reset();
      this.getUserList()
      this.getChannelList()
      this.mobilePluginsProp.showAddOrModDialog = true
      this.mobilePluginsProp.dialogTitle = "新增版本信息"
    },
    mobileModify (row) {
      this.reset();
      this.getUserList()
      this.getChannelList()
      getFbInfo(row.pkId).then(response => {
        this.form = response.data;
        this.form.channelListIds = this.handleSelectIds(this.form.channelListIds)
        this.mobilePluginsProp.showAddOrModDialog = true
        this.mobilePluginsProp.dialogTitle = "修改版本信息"
      });
    },
    /** 提交按钮 */
    onSubmitMobileForm() {
      if (typeof this.form.channelListIds === 'object') {
        this.form.channelListIds = this.form.channelListIds.join(',')
      }
      if (this.form.pkId != null) {
        updateFbInfo(this.form).then(response => {
          if (response.code === 200) {
            Notify({ type: 'success', message: '修改成功' });
            this.mobilePluginsProp.showAddOrModDialog = false
            var index = this.fbInfoList.findIndex(r => r.pkId === this.form.pkId)
            getFbInfo(this.form.pkId).then(response => {
              var row = response.data
              this.formatFbTypeCommon(row)
              this.fbInfoList[index] = row
              this.fbInfoList = this.fbInfoList.slice()
            })
          } else {
            Notify({ type: 'danger', message: response.msg });
          }
        });
      } else {
        addFbInfo(this.form).then(response => {
          if (response.code === 200) {
            Notify({ type: 'success', message: '新增成功' });
            this.mobilePluginsProp.showAddOrModDialog = false
            this.mobileGetList(true)
          } else {
            Notify({ type: 'danger', message: response.msg });
          }
        });
      }
    },
    handleSelectIds (ids) {
      if (!ids) {
        return []
      }
      var idsArr = ids.split(',')
      var newArr = []
      idsArr.forEach(e => {
        newArr.push(Number(e))
      })
      return newArr
    }
  }
};
</script>
<style scoped>
.btns .filter-time_btn {
  margin-bottom: 20px;
  width: 100%;
}
</style>

